package com.polito.mad.bikeponyapp.fragments;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.polito.mad.bikeponyapp.R;
import com.polito.mad.bikeponyapp.persistence.DeliveryItem;
import com.polito.mad.bikeponyapp.util.DeliveriesFacade;

public class AdditionalInfoFragment extends Fragment{

	private DeliveriesFacade facade;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.additional_info_fragment_layout, container,false);
		return v;
	}
	@Override
	public void onStart() {
		super.onStart();
		updateView(getView(), -1);
	}
	private void updateView(View v,Integer selectedItem) {
		if(selectedItem==null || selectedItem==-1 )
			selectedItem = facade.getItemSelected();
		if(selectedItem==-1)
			selectedItem = 0;
		String name = "---";
		String more = "";
		if(facade.getItems()!=null && facade.getItems().size()>selectedItem && selectedItem!=-1)
		{
			DeliveryItem showItem = facade.getItems().get(selectedItem);
			String addInfo = showItem.getAdditionalInfo();
			
			try {
				JSONObject jo = new JSONObject(addInfo);
				name = jo.get("name")+" "+jo.getString("surname");
				if(!jo.getString("more").isEmpty())
				{
					more = jo.getString("more");
				}
			} catch (JSONException e) {
				//ignoring if there is no name/data
			}
		}
		TextView tvAdditionalInfoName = (TextView) v.findViewById(R.id.additionalinfo_name);
		tvAdditionalInfoName.setText(name);
		
		TextView tvAdditionalInfoMore = (TextView) v.findViewById(R.id.additionalinfo_more);
		if(!more.isEmpty())
		{
			tvAdditionalInfoMore.setVisibility(View.VISIBLE);
			TextView addInfoMoreLabel = (TextView) v.findViewById(R.id.additional_info_more_label);
			addInfoMoreLabel.setVisibility(View.VISIBLE);
			
			tvAdditionalInfoMore.setText(more);
		}
		else
		{
			tvAdditionalInfoMore.setVisibility(View.GONE);
			TextView addInfoMoreLabel = (TextView) v.findViewById(R.id.additional_info_more_label);
			addInfoMoreLabel.setVisibility(View.GONE);
			
		}
		getView().invalidate();
		getActivity().findViewById(R.id.container).requestLayout();
	}
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		facade = (DeliveriesFacade)activity;
		
	}
	public void updateShownItemDetails(Integer selectedItemMarker)
	{
		updateView(getView(),selectedItemMarker);
	}
}
